package cn.net.isir.common.pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.FileItem;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import cn.net.isir.common.config.AlipayConfig;
import cn.net.isir.utils.StringUtils;

/**
 * @author liuxubo
 * @filename AlipayAPI.java
 * @package cn.net.isir.common.pay.alipay
 * @email lxb@isir.net.cn
 * @date 2018/11/14
 * @comment 支付宝用到的API列表
 * @since 1.8
 */
public class AlipayAgentAPI {
    // 声明log4j日志
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(AlipayAgentAPI.class);
    /**
     * 获取业务SDK
     */
    private static AlipayClient alipayClient = AlipayClientUtils.getAlipayClient();

    /**
     * 获取用于支付的sdk
     */
    private static AlipayClient alipayPayClient = AlipayClientUtils.getAlipayPayClient();

    /**
     * alipay.open.agent.facetoface.sign(代签约当面付产品)
     * <p><b>三方应用代理签约当面付产品，需要配合开启事务接口使用</b></p>
     * <p>https://docs.open.alipay.com/api_50/alipay.open.agent.facetoface.sign/</p>
     *
     * @param batch_no                            代商户操作事务编号，通过alipay.open.isv.agent.create接口进行创建。
     * @param mcc_code                            所属MCCCode，详情可参考商家经营类目 中的“经营类目编码”
     *                                            <p>https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.59bgD2&treeId=222&articleId=105364&docType=1</p>
     * @param special_license_pic_file_path       企业特殊资质图片，可参考商家经营类目 中的“需要的特殊资质证书”，最小5KB，图片格式必须为：png、bmp、gif、jpg、jpeg
     * @param business_license_no                 营业执照号码
     * @param business_license_pic_file_path      营业执照图片。被代创建商户运营主体为个人账户必填，企业账户无需填写，最小5KB，图片格式必须为：png、bmp、gif、jpg、jpeg
     * @param business_license_auth_pic_file_path 营业执照授权函图片，个体工商户如果使用总公司或其他公司的营业执照认证需上传该授权函图片，最小5KB，图片格式必须为：png、bmp、gif、jpg、jpeg
     * @param shop_sign_board_pic_file_path       店铺门头照图片，最小5KB，图片格式必须为：png、bmp、gif、jpg、jpeg
     */
    public static AlipayOpenAgentFacetofaceSignResponse alipayOpenAgentFacetofaceSign(String app_auth_token, String batch_no, String mcc_code, String special_license_pic_file_path,
                                                                                      String business_license_no, String business_license_pic_file_path,
                                                                                      String business_license_auth_pic_file_path, String shop_sign_board_pic_file_path) {
        AlipayOpenAgentFacetofaceSignRequest request = new AlipayOpenAgentFacetofaceSignRequest();
        request.setBatchNo(batch_no);
        request.setMccCode(mcc_code);
        // 判断是否有特殊资质,如果有,则需要填写
        if (StringUtils.isNotBlank(special_license_pic_file_path)) {
            FileItem SpecialLicensePic = new FileItem(special_license_pic_file_path);
            request.setSpecialLicensePic(SpecialLicensePic);
        }
        request.setBusinessLicenseNo(business_license_no);
        FileItem BusinessLicensePic = new FileItem(business_license_pic_file_path);
        request.setBusinessLicensePic(BusinessLicensePic);
        FileItem BusinessLicenseAuthPic = new FileItem(business_license_auth_pic_file_path);
        request.setBusinessLicenseAuthPic(BusinessLicenseAuthPic);
//        request.setLongTerm(true);
//        request.setDateLimitation("2017-11-11");
//        FileItem ShopScenePic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
//        request.setShopScenePic(ShopScenePic);
        FileItem ShopSignBoardPic = new FileItem(shop_sign_board_pic_file_path);
        request.setShopSignBoardPic(ShopSignBoardPic);
        AlipayOpenAgentFacetofaceSignResponse response = null;
        try {
            //使用商户token
//            request.putOtherTextParam("app_auth_token", app_auth_token);
            response = alipayPayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error("代签约当面付产品", e);
        }
        return (AlipayOpenAgentFacetofaceSignResponse) getResponse(response);
    }

    //extend_params


    /**
     * alipay.trade.create(统一收单交易创建接口)
     * <p><b>商户通过该接口进行交易的创建下单</b></p>
     * <p>https://docs.open.alipay.com/api_1/alipay.trade.create/</p>
     *
     * @param app_auth_token          商户授权的app_auth_token
     * @param out_trade_no            商户订单号,64个字符以内、只能包含字母、数字、下划线；需保证在商户端不重复
     * @param seller_id               卖家支付宝用户ID。如果该值为空，则默认为商户签约账号对应的支付宝用户ID
     * @param total_amount            订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000] 如果同时传入了【打折金额】，【不可打折金额】，【订单总金额】三者，则必须满足如下条件：【订单总金额】=【打折金额】+【不可打折金额】
     * @param subject                 订单标题,例如：Iphone6 16G
     * @param sys_service_provider_id 系统商编号，该参数作为系统商返佣数据提取的依据，请填写系统商签约协议的PID
     */
    public static AlipayTradeCreateResponse alipayTradeCreate(String app_auth_token,
                                                              String out_trade_no,
                                                              String seller_id,
                                                              String buyer_id,
                                                              String total_amount,
                                                              String subject,
                                                              String sys_service_provider_id) {
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        JSONObject body = new JSONObject();
        body.put("out_trade_no", out_trade_no);
        body.put("seller_id", seller_id);
        body.put("buyer_id", buyer_id);
        body.put("total_amount", total_amount);
        body.put("subject", subject);
        JSONObject subBody = new JSONObject();
        subBody.put("sys_service_provider_id", sys_service_provider_id);
        body.put("extend_params", subBody);
        request.setBizContent(body.toJSONString());
        AlipayTradeCreateResponse response = null;
        try {
            request.putOtherTextParam("notify_url", AlipayConfig.getPay_notify_url_pay());
            request.putOtherTextParam("app_auth_token", app_auth_token);
            response = alipayPayClient.execute(request);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return (AlipayTradeCreateResponse) getResponse(response);
    }

    /**
     * 公共判断方法
     *
     * @param response 返回
     * @return 返回response或者null
     */
    private static AlipayResponse getResponse(AlipayResponse response) {
        if (response != null) {
            if (response.isSuccess()) {
                logger.info("调用成功");
                return response;
            } else {
                logger.info("调用失败");
            }
        }
        return null;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("batch_no", "asdfasdasf");
        logger.info(jsonObject.toJSONString());
    }
}
